<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############




// this page uses $scanFiles as session storage of files destined to $pData[2]
global $scanFiles;

if(!isset($_SESSION['JFX_Module_Vms_ScanFilesTemp']) || !is_array($_SESSION['JFX_Module_Vms_ScanFilesTemp'])){
    $_SESSION['JFX_Module_Vms_ScanFilesTemp'] = array();
}
$scanFiles =& $_SESSION['JFX_Module_Vms_ScanFilesTemp'];














if(get('reset')==2){

    if(Antz_IntelliForm::submitted('confirm-reset')){
        $pData[2] = array();
        $pData[3] = array();
        $pData[4] = array();
        unset($_SESSION['JFX_Module_Vms_ScanFilesTemp'], $_SESSION['JFX_Module_Vms_ScanFilesAuto']);
        JFX::redirect($this->adminUrl.'/new-version/');
    }


    $formFields = array(
        array(
            'type' => 'submit',
            'name' => 'submitBtn',
            'label' => '&nbsp;',
            'value' => 'Reset Included Files'
        )
    );

    echo JFX::makeRapidForm($formFields, 'Confirm Reset', 'confirm-reset');

    return;
}















// auto-load from previous version


$versionData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_versions WHERE package_id = '{$pData[1]['package_id']}' ORDER BY version DESC LIMIT 1");
$packageData = $DB->fetchRow("SELECT * FROM {$CONFIG->dbprefix}vms_packages WHERE id = '{$pData[1]['package_id']}'");



// makes sure the files only get auto-populated once or will not be able to delete entries from $scanFiles
if(!isset($_SESSION['JFX_Module_Vms_ScanFilesAuto'])) $_SESSION['JFX_Module_Vms_ScanFilesAuto'] = NULL;

$uniqueString = (string) serialize($versionData).(string) serialize($packageData);

if($_SESSION['JFX_Module_Vms_ScanFilesAuto'] !== $uniqueString){
    // runs this once

    if(is_array($versionData) && count($versionData)>0){
        $version = $vData['version'];

        $files = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}vms_files WHERE package_id = '{$pData[1]['package_id']}' AND version_id = '{$versionData['id']}'");

        eval('$basePath = "'.$packageData['base_path'].'";');

        if(is_array($files) && count($files)>0){
            foreach($files as $k=>$v){
                $filepath = rtrim($basePath, '/').'/'.ltrim($v['filename'], '/');
                if(is_dir($filepath)){
                    $scanFiles[] = $filepath;
                }else if(file_exists($filepath) && is_readable($filepath)){
                    $scanFiles[] = $filepath;
                }
            }
        }
    }


    $_SESSION['JFX_Module_Vms_ScanFilesAuto'] = $uniqueString;

}



















eval('$path = "'.$packageData['base_path'].'";');


if(!isset($path)) $path = '';

if(array_key_exists('path', $_GET)) $path = get('path');

if($path == '') $path = $CONFIG->modulesDir;

$pathParts = explode('/', $path);
foreach($pathParts as $k=>$v){
    if($v == '..'){
        unset($pathParts[$k], $pathParts[$k-1]);
    }
}

$pathParts = array_regenerate_keys($pathParts);
$path = implode('/', $pathParts);



if(Antz_IntelliForm::submitted('finished-importing-files')){
    // finished building temporary list, save and move to next step
    $pData[2] = $scanFiles;
    unset($_SESSION['JFX_Module_Vms_ScanFilesTemp'], $_SESSION['JFX_Module_Vms_ScanFilesAuto']);
    JFX::redirect($this->adminUrl.'/new-version/');
}


if(Antz_IntelliForm::submitted('vms-scan-files')){
    // wanting to add or remove files from the temporary list
    $recursive = (bool) post('recursive', 0);

    $dh = opendir($path);
    $dirs = array();
    while($file = readdir($dh)){
        if($file == '.') continue;
        if(is_dir($path.'/'.$file)) $prefix = 0;
        else $prefix = 1;
        $dirs[$prefix.$file] = $file;
    }

    ksort($dirs);
    $dirs = array_regenerate_keys($dirs);
    $numAdded = 0;
    $numRemoved = 0;

    foreach($dirs as $k=>$v){
        if($v == '..') continue;
        $included = (int) post('scanfile_'.$k);

        if($included == 0 && in_array($path.'/'.$v, $scanFiles)){
            $flipped = array_flip($scanFiles);
            unset($scanFiles[$flipped[$path.'/'.$v]]);
            $numRemoved++;
            if($recursive && is_dir($path.'/'.$v)){
                VMS_ScanFolder_RecurseOutofScanFolders($scanFiles, $path.'/'.$v, $numRemoved);
            }
        }else if($included == 1){
            $scanFiles[] = $path.'/'.$v;
            $numAdded++;
            if($recursive && is_dir($path.'/'.$v)){
                VMS_ScanFolder_RecurseIntoScanFolders($scanFiles, $path.'/'.$v, $numAdded);
            }
        }
    }

    JFX::addSuccess($numAdded.' files have been added, '.$numRemoved.' removed');
    unset($pData[2]);
    JFX::redirect(THIS_PAGE_URL);
}
/*
echo '<pre>';
var_dump($scanFiles);
echo '</pre>';
*/
echo VMS_ScanFolder_MakeLinks($path, $this->adminUrl, $scanFiles);


if((string) serialize($pData[2]) === (string) serialize($scanFiles)){

}else{
    // show the update button
echo '
<div class="finished-selecting-files-button">
    <form method="post">'.Antz_IntelliForm::seed('finished-importing-files').'
        <input type="submit" value="Save" />
    </form>
</div>';
}





















function VMS_ScanFolder_RecurseIntoScanFolders(&$scanFiles, $dirname, &$numFiles){
    $dh = opendir($dirname);
    while($file = readdir($dh)){
        if($file == '..' || $file == '.') continue;
        if(!in_array($dirname.'/'.$file, $scanFiles)){
            $numFiles++;
            $scanFiles[] = $dirname.'/'.$file;
        }
        if(is_dir($dirname.'/'.$file)) VMS_ScanFolder_RecurseIntoScanFolders($scanFiles, $dirname.'/'.$file, $numFiles);
    }
}


function VMS_ScanFolder_RecurseOutofScanFolders(&$scanFiles, $dirname, &$numFiles){
    $dh = opendir($dirname);
    while($file = readdir($dh)){
        if($file == '..' || $file == '.') continue;
        if(in_array($dirname.'/'.$file, $scanFiles)){
            $flipped = array_flip($scanFiles);
            unset($scanFiles[$flipped[$dirname.'/'.$file]]);
            $numFiles++;
        }
        if(is_dir($dirname.'/'.$file)) VMS_ScanFolder_RecurseOutofScanFolders($scanFiles, $dirname.'/'.$file, $numFiles);
    }
}














function VMS_ScanFolder_MakeLinks($path, $url, $scanFiles){
    $CONFIG = JFX::registry('config');
    $VIEW = JFX::registry('JFX_View');

    $js = <<<JS
function VMS_CheckInclude(){
    $('input[type=radio]').each(function(){
        if(this.value == 0) this.checked = false;
        else this.checked = true;
    });
}
function VMS_CheckExclude(){
    $('input[type=radio]').each(function(){
        if(this.value == 0) this.checked = true;
        else this.checked = false;
    });
}
JS;

    $VIEW->addJs($js);

    $imgUrl = $CONFIG->baseUrl.$CONFIG->moduleImageFolder;

    $dh = opendir($path);
    $dirs = array();
    while($file = readdir($dh)){
        if($file == '.') continue;
        if(is_dir($path.'/'.$file)) $prefix = 0;
        else $prefix = 1;
        $dirs[$prefix.$file] = $file;
    }

    ksort($dirs);
    $dirs = array_regenerate_keys($dirs);

    $output = '<div class="vms-scan-files-path">'.$path.'</div>';
    $output .= '<form method="post"><input type="hidden" name="scanfolder" value="'.$path.'" />'.Antz_IntelliForm::seed('vms-scan-files');
    $output .= '<table><tbody>';

    foreach($dirs as $k=>$file){
        if(in_array($path.'/'.$file, $scanFiles)){
            $included = ' checked="checked" ';
            $excluded = '';
        }else{
            $included = '';
            $excluded = ' checked="checked" ';
        }
        if(is_dir($path.'/'.$file)){
            $aOpen = '<img src="'.$imgUrl.'/vms/folder.png" alt="Folder" class="folder-icon" /><a href="'.$url.'/new-version/scan-folder/?path='.$path.'/'.$file.'">';
            $aClose = '</a>';
        }else{
            $aOpen = '';
            $aClose = '';
        }
        $output .= '<tr>
            <td><div align="left">'.$aOpen.$file.$aClose.'</div></td>
            ';
        if($file == '..'){
            $output .= '<td class="radio">
                <a href="javascript: void(null);" onclick="VMS_CheckInclude()">Include</a>
            </td><td class="radio">
                <a href="javascript: void(null);" onclick="VMS_CheckExclude()">Exclude
            </td></tr>';
        }else{
            $output .= '<td><input type="radio" name="scanfile_'.$k.'" value="1" '.$included.' /></td>
            <td><input type="radio" name="scanfile_'.$k.'" value="0" '.$excluded.' /></td>
        </tr>';
        };
    }

    $output .= '<tr><td>&nbsp;</td><td colspan="2">
        <div align="left"><label><input type="checkbox" name="recursive" value="1" />Recursive</label></div>
        <div align="center"><input type="submit" name="submitBtn" value="Add / Remove Selected" /></div>
    </td></tr>';

    $output .= '</tbody></table>';
    $output .= '</form>';

    return $output;
}


